/**
 * Copyright : www.orientpay.com , 2007-2011
 * Project : sqt_spider_main
 * $Id$
 * $Revision$
 * Last Changed by ZhouXushun at 2011-5-10 下午03:09:39
 * $URL$
 * 
 * Change Log
 * Author      Change Date    Comments
 *-------------------------------------------------------------
 * ZhouXushun     2011-5-10        Initailized
 */

package com.youthor.spider.core.monitor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.youthor.spider.core.dto.HttpProxyDTO;

/**
 * 代理持有类
 *
 */
public class HttpProxyHolder {
	private static HttpProxyHolder instance;
	
	private List<HttpProxyDTO> httpProxyDTOList;
	//正在使用的代理次数信息
	Map<String, Integer> usingHttpProxyDTOMap;
	private boolean isLocked;
	
	private HttpProxyHolder(){
		httpProxyDTOList = new ArrayList<HttpProxyDTO>();
		usingHttpProxyDTOMap = new HashMap<String, Integer>();
	}
	
	public static synchronized HttpProxyHolder getInstance(){
		if(instance == null){
			instance = new HttpProxyHolder();
		}
		return instance;
	}
	
	public void addHttpProxyDTO(HttpProxyDTO dto){
		httpProxyDTOList.add(dto);
	}
	
	public void removeHttpProxyDTO(HttpProxyDTO dto){
		httpProxyDTOList.remove(dto);
		usingHttpProxyDTOMap.remove(dto.toString());
	}
	
	public void removeAll(){
		httpProxyDTOList.clear();
		usingHttpProxyDTOMap.clear();
	}

	public boolean isLocked() {
		return isLocked;
	}

	public void setLocked(boolean isLocked) {
		this.isLocked = isLocked;
	}
	
	public void releaseHttpProxy(String proxyInfo){
		if(usingHttpProxyDTOMap.containsKey(proxyInfo)){
			int time = usingHttpProxyDTOMap.get(proxyInfo);
			if(time > 0){
				time--;
				usingHttpProxyDTOMap.put(proxyInfo, time);
			}
		}
	}
	
	public HttpProxyDTO getHttpProxyDTO(){
		//计算权重
		int minIndex = -1;
		int min = -1;
		
		for(int i=0, len = httpProxyDTOList.size(); i < len; i++){
			HttpProxyDTO dto = httpProxyDTOList.get(i);
			int proportion = 1;
			if(usingHttpProxyDTOMap.containsKey(dto.toString())){
				proportion = (1 + usingHttpProxyDTOMap.get(dto.toString())) * dto.getProportion();
			}
			if(i == 0){
				minIndex = 0;
				min = proportion;
				continue;
			}
			if(proportion < min){
				minIndex = i;
				min = proportion;
			}
		}
		
		if(minIndex == -1){
			return null;
		}
		
		HttpProxyDTO dto = httpProxyDTOList.get(minIndex);
		String key = dto.toString();
		int time = 0;
		if(usingHttpProxyDTOMap.containsKey(key)){
			time = usingHttpProxyDTOMap.get(key);
		}
		time++;
		usingHttpProxyDTOMap.put(key, time);
		return dto;
	}
}
